package com.xcity.game.arena.online;

import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

import com.xcity.db.entity.Player;
import com.xcity.db.entity.Ranking;
import com.xcity.game.arena.ArenaHandler;
import com.xcity.game.arena.online.model.RankingPlayer;
import com.xcity.game.arena.online.model.Schedule;
import com.xcity.game.arena.online.template.ArenaOpenTimeTemplate;
import com.xcity.game.rank.RankingListEnum;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.request.ArenaOnlineDailyRewardRequest;
import com.xcity.pomelo.request.ArenaOnlineDailyRewardsInfoRequest;
import com.xcity.pomelo.request.ArenaOnlineInfoRequest;
import com.xcity.pomelo.request.ArenaOnlineRankingListRequest;
import com.xcity.pomelo.request.ArenaOnlineSegmentsRequest;
import com.xcity.pomelo.request.ArenaOnlineTop3Request;
import com.xcity.pomelo.response.ArenaOnlineInfoResponse;
import com.xcity.pomelo.response.ArenaOnlineInfoResponse.DayRange;
import com.xcity.pomelo.response.ArenaOnlineInfoResponse.Time;

import naga.x.App;
import naga.x.game.template.TemplateService;
import naga.x.game.time.DayListener;
import naga.x.game.time.TimeUpdater;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;
import naga.x.util.TimeUtils;

@OPHandler
public class OnlineArenaHandler implements ArenaHandler, DayListener {
	
	private Queue<Player>[] pendingMatches; // 进入匹配状态的玩家列表，按段位分组
	// 开启时间表
	private List<Schedule> schedules;
	// 全服排行榜
	private List<RankingPlayer> globalRankings;
	
	private List<ArenaOpenTimeTemplate> scheduleTemplates = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(ArenaOpenTimeTemplate.class);

	@Override
	public void startup() throws ServiceException {
		initSchedule();
		TimeUpdater.getInstance().addDayListener(this);
	}

	@Override
	public void shutdown() throws ServiceException {
	}

	@Override
	public String getId() {
		return getClass().getName();
	}
	
	@Override
	public boolean dayChanged() {
		Calendar cal = Calendar.getInstance();
		if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
			// 每周一凌晨重置时间表
			initSchedule();
		}
		return true;
	}
	
	private void initSchedule() {
		List<Schedule> schedulesNewer = new LinkedList<Schedule>();
		long mondayZeroTime = TimeUtils.getMondayZeroTime();
		for (int i = 0; i < scheduleTemplates.size(); i++) {
			ArenaOpenTimeTemplate template = scheduleTemplates.get(i);
			// 周一~周日(1~7)
			for (int day = template.getDayFrom(); day <= template.getDayTo(); day++) {
				long[] times = template.getTimesMillis();
				for (int j = 0; j < times.length; j += 2) {
					long offset = TimeUnit.DAYS.toMillis(day - 1); // day offset
					long beginTime = mondayZeroTime + times[j] + offset;
					long endTime = mondayZeroTime + times[j + 1] + offset;
					schedulesNewer.add(new Schedule(beginTime, endTime));
				}
			}
		}
		schedules = schedulesNewer;
//		printSchedules();
	}
	
	private void printSchedules() {
		System.out.println("在线竞技时间表：");
		for (Schedule sch : schedules) {
			System.out.println(sch);
		}
	}
	
	public boolean isOpened() {
		for (Schedule sch : schedules) {
			if (sch.enable()) {
				return true;
			}
		}
		return false;
	}
	
	public RankingPlayer findGlobalRanking(long id) {
		List<RankingPlayer> rankings = globalRankings;
		for (int i = rankings.size() - 1; i >= 0; i--) {
			RankingPlayer rp = rankings.get(i);
			if (id == rp.id) {
				return rp;
			}
		}
		return null;
	}

	@PomeloOP(PomeloRoute.ARENA_ONLINE_INFO)
	protected void requestInfo(Session session, ArenaOnlineInfoRequest req) {
		Player player = session.getClient();
		ArenaOnlineInfoResponse res = new ArenaOnlineInfoResponse(req.getSerial());
		// 比赛时间
		res.times = new DayRange[scheduleTemplates.size()];
		for (int i = 0; i < scheduleTemplates.size(); i++) {
			ArenaOpenTimeTemplate template = scheduleTemplates.get(i);
			DayRange range = res.times[i] = new DayRange();
			range.dayFrom = template.getDayFrom();
			range.dayTo = template.getDayTo();
			String[] times = template.getTimes();
			range.times = new Time[times.length >> 1];
			for (int j = 0; j < times.length; j += 2) {
				Time time = range.times[j >> 1] = new Time();
				time.from = times[j];
				time.to = times[j + 1];
			}
		}
		// 本服排名
		Ranking ranking = RankingListEnum.ARENA_ONLINE.instance.findEntry(player.getId());
		res.rank = ranking != null ? ranking.getIndex() : -1;
		// 全服排名
		RankingPlayer globalRanking = findGlobalRanking(player.getId());
		res.globalRank = globalRanking != null ? globalRanking.ranking : -1;
		// 本赛季历史最高段位
//		res.topSegment = 
	}
	
	@PomeloOP(PomeloRoute.ARENA_ONLINE_SEGMENT_INFO)
	protected void requestSegments(Session session, ArenaOnlineSegmentsRequest req) {
//		ArenaOnlineSegmentsResponse
	}
	
	@PomeloOP(PomeloRoute.ARENA_ONLINE_DAILY_REWARDS_INFO)
	protected void requestDailyRewards(Session session, ArenaOnlineDailyRewardsInfoRequest req) {
//		ArenaOnlineDailyRewardsInfoResponse
	}

	@PomeloOP(PomeloRoute.ARENA_ONLINE_DAILY_REWARD_GET)
	protected void requestDailyReward(Session session, ArenaOnlineDailyRewardRequest req) {
//		ArenaOnlineDailyRewardResponse
	}
	
	@PomeloOP(PomeloRoute.ARENA_ONLINE_RANKING_LIST)
	protected void requestRankingList(Session session, ArenaOnlineRankingListRequest req) {
//		ArenaOnlineRankingListResponse
	}
	
	@PomeloOP(PomeloRoute.ARENA_ONLINE_TOP3)
	protected void requestTop3(Session session, ArenaOnlineTop3Request req) {
//		ArenaOnlineTop3Response
	}

}
